package com.toptime.cloudhelper.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.*;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private MeterRegistry registry;

    @RequestMapping("/order")
    public Object order() {
        String[] ips = {"127.0.0.1", "10.100.111.10", "10.100.111.11", "10.100.111.12", "10.100.111.13"};
        String ip = ips[new Random().nextInt(ips.length)];
        Counter counter = registry.counter("app_order_count", "ip", generateRandomIP());
        counter.increment();
        return "OK";
    }

    @RequestMapping("/url")
    public Object url() {
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        String accessKey = "LTAI5tLerDsxKUKsom4i8XBg";
        String accessSecret = "WaJldzXglJwhm2XM3iNzzSRLDzoA8T";
        String bucketName = "geek-demo";
        String objectName = "/test/git.png";
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, 1);
        Date expiration = calendar.getTime();
        OSS client = new OSSClientBuilder().build(endpoint, accessKey, accessSecret);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
        request.setExpiration(expiration);
        URL url = client.generatePresignedUrl(request);
        client.shutdown();
        Map<String, Object> result = new HashMap<>();
        result.put("url", url);
        return result;
    }

    public static String generateRandomIP() {
        Random random = new Random();
        int first = random.nextInt(256);
        int second = random.nextInt(256);
        int third = random.nextInt(256);
        int fourth = random.nextInt(256);
        return first + "." + second + "." + third + "." + fourth;
    }
}
